/* =============================================================
 * System Name：Document Control System
 * File Name： WeiboUserPopulator.java
 * --------------------------------------------------------------
 * (C) Copyright M+W Group 2012 All Rights Reserved.
 *
 *  VERSION    DATE        BY                CHANGE/COMMENT
 * ----------------------------------------------------------------
 *
 */
package com.deco.authorization.user;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

/**
 * Sina weibo user information extractor.
 * 
 * @author $Author: Kevin Zhu <kevin.zhu@mwgroup.net>$
 * @version $Revision: 1.07$
 */
public class RenrenUserPopulator implements UserPopulator {
	private static final Pattern USERID_REGEX = Pattern
			.compile("\"id\":([^,]+)");
	private static final Pattern USERNAME_REGEX = Pattern
	.compile("\"name\":\"([^,]+)\",");

	public OAuthUser populateUser(Token token,OAuthService service) {
		String userId = extract(token.getRawResponse(), USERID_REGEX);
		String userName = extract(token.getRawResponse(), USERNAME_REGEX);
		
		return new OAuthUser(userId, userName, userName, "Renren");
	}

	private String extract(String response, Pattern p) {
		Matcher matcher = p.matcher(response);
		if (matcher.find() && matcher.groupCount() >= 1) {
			return matcher.group(1);
		} else {
			return null;
			// throw new
			// OAuthException("Response body is incorrect. Can't extract user information from this: '"
			// + response + "'", null);
		}
	}

}
